package com.lsp.lib_uikit.commonrecycler;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.util.Log;
import com.lsp.lib_uikit.commonrecycler.defaultview.DefaultFooterView;
import com.lsp.lib_uikit.commonrecycler.defaultview.LoadingMoreFooterBase;

/**
 * 带加载更多功能的recyclerview
 * 下拉可以配合ptr
 * tips:需要在配合使用下拉的时候禁止掉上拉  否则容易出错
 *
 * @author lsp
 * @created 16/10/12 16:17
 */
public class LoadMoreRecyclerView extends BaseRecyclerView {

  private LoadingMoreFooterBase mFootView;
  private LoadMoreWrapper loadMoreWrapper;
  private boolean loadingMoreEnabled = true;//默认带上拉加载更多
  private final RecyclerView.AdapterDataObserver mDataObserver = new DataObserver();

  public LoadMoreRecyclerView(Context context) {
    super(context);
  }

  public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
  }

  public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }


  /**
   * 设置默认的上拉加载view
   */
  private void useDefaultFooter() {
    mFootView = new DefaultFooterView(getContext());
    setFootView(mFootView);
  }

  @Override public void setAdapter(Adapter adapter) {
    loadMoreWrapper = new LoadMoreWrapper(adapter);
    if (null == mFootView) {
      useDefaultFooter();
    }
    super.setAdapter(loadMoreWrapper);
    adapter.registerAdapterDataObserver(mDataObserver);
    mDataObserver.onChanged();
  }

  @Override public void onScrollStateChanged(int state) {
    super.onScrollStateChanged(state);
    if (state == RecyclerView.SCROLL_STATE_IDLE
        && mOnLoadingMoreListener != null
        && loadingMoreEnabled
        && mFootView.getLoadmoreStatus() != LoadingMoreFooterBase.PULL_UP_LOADING) {
      LayoutManager layoutManager = getLayoutManager();
      int lastVisibleItemPosition;
      if (layoutManager instanceof GridLayoutManager) {
        lastVisibleItemPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition();
      } else if (layoutManager instanceof StaggeredGridLayoutManager) {
        int[] into = new int[((StaggeredGridLayoutManager) layoutManager).getSpanCount()];
        ((StaggeredGridLayoutManager) layoutManager).findLastVisibleItemPositions(into);
        lastVisibleItemPosition = findMax(into);
      } else {
        lastVisibleItemPosition =
            ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
      }
      if (layoutManager.getChildCount() > 0
          && lastVisibleItemPosition >= layoutManager.getItemCount() - 1
          && layoutManager.getItemCount() > layoutManager.getChildCount()
          && mFootView.getLoadmoreStatus() != LoadingMoreFooterBase.PULL_UP_COMPLETE) {
        mFootView.setLoadmoreStatus(LoadingMoreFooterBase.PULL_UP_LOADING);
        mFootView.onLoadLoading();

        mOnLoadingMoreListener.onLoadingMore();
      }
    }
  }

  private int findMax(int[] lastPositions) {
    int max = lastPositions[0];
    for (int value : lastPositions) {
      if (value > max) {
        max = value;
      }
    }
    return max;
  }

  /**
   * 需要在setAdapter之后调用否则不能生效
   */
  public void setFootView(LoadingMoreFooterBase view) {
    mFootView = view;
    if (loadMoreWrapper != null) {
      loadMoreWrapper.setLoadMoreView(view);
    } else {
      Log.e("error", "#setFootView() need set after #setAdapter()");
    }
  }

  /**
   * 设置是否允许加载更多
   */
  public void setLoadingMoreEnabled(boolean enabled) {
    loadingMoreEnabled = enabled;
    if (!enabled) {
      //TODO--不允许上拉加载更多
    }
  }

  public interface OnLoadingMoreListener {
    void onLoadingMore();
  }

  private OnLoadingMoreListener mOnLoadingMoreListener;

  public void setOnLoadingMoreListener(OnLoadingMoreListener onLoadingMoreListener) {
    mOnLoadingMoreListener = onLoadingMoreListener;
  }

  /**
   * 加载完成时调用
   *
   * @param hasMore 是否还有更多数据
   */
  public void loadMoreFinish(boolean hasMore) {

    if (mFootView != null) {
      if (hasMore) {
        mFootView.setLoadmoreStatus(LoadingMoreFooterBase.PULL_UP_LOAD_IDLE);
      } else {
        mFootView.setLoadmoreStatus(LoadingMoreFooterBase.PULL_UP_COMPLETE);
      }
      mFootView.onLoadFinish(hasMore);
    }
  }

  /**
   * 加载失败时调用
   */
  public void loadMoreError(String errorString) {

    if (mFootView != null) {
      mFootView.setLoadmoreStatus(LoadingMoreFooterBase.PULL_UP_FAIL);
      mFootView.onLoadError();
    }
  }

  private class DataObserver extends RecyclerView.AdapterDataObserver {
    @Override public void onChanged() {
      if (loadMoreWrapper != null) {
        loadMoreWrapper.notifyDataSetChanged();
      }
    }

    @Override public void onItemRangeInserted(int positionStart, int itemCount) {
      loadMoreWrapper.notifyItemRangeInserted(positionStart, itemCount);
    }

    @Override public void onItemRangeChanged(int positionStart, int itemCount) {
      loadMoreWrapper.notifyItemRangeChanged(positionStart, itemCount);
    }

    @Override public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
      loadMoreWrapper.notifyItemRangeChanged(positionStart, itemCount, payload);
    }

    @Override public void onItemRangeRemoved(int positionStart, int itemCount) {
      loadMoreWrapper.notifyItemRangeRemoved(positionStart, itemCount);
    }

    @Override public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
      loadMoreWrapper.notifyItemMoved(fromPosition, toPosition);
    }
  }
}
